package com.dhh.sky.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.dhh.sky.R;
import com.dhh.sky.dao.DataBaseHelper;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.model.SkyDrivePhoto;
import com.dhh.sky.util.FileManager;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.DecodingType;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

public class ImagePagerActivity extends Activity {
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private ViewPager pager;
    private ActionBar actionBar;
    private String[] names;
    private String[] ids;
    private int pagerPosition;
    private FileManager fManager;
	private DataBaseHelper db;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ac_image_pager);
		Bundle bundle = getIntent().getExtras();
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
		fManager = new FileManager(db);
		String[] imageUrls = bundle.getStringArray("imageUrls");
		names = bundle.getStringArray("names");
		ids = bundle.getStringArray("ids");
		pagerPosition = bundle.getInt("IMAGE_POSITION", 0);
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
			.showImageForEmptyUrl(R.drawable.image_for_empty_url)
			.cacheOnDisc()
			.decodingType(DecodingType.MEMORY_SAVING)
			.build();

		pager = (ViewPager) findViewById(R.id.pager);
		pager.setOnPageChangeListener(new OnPageChangeListener(){

			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				pagerPosition = position;
				actionBar.setTitle(names[pagerPosition]);
			}

			@Override
			public void onPageSelected(int arg0) {
				
			}});
		pager.setAdapter(new ImagePagerAdapter(imageUrls));
		pager.setCurrentItem(pagerPosition);
		
		initActionBar();
	}

	@Override
	protected void onStop() {
		imageLoader.stop();
		super.onStop();
	}
	
	private void initActionBar(){
		actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new HomeAction());
		actionBar.addAction(new DownloadAction());
		actionBar.setTitle(names[pagerPosition]);
	}
	
	private class HomeAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_home_arrow;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
			SlideoutActivity.prepare(ImagePagerActivity.this, R.id.inner_content, width);
			startActivity(new Intent(ImagePagerActivity.this,MenuActivity.class));
			overridePendingTransition(0, 0);
	    }
	}
	
	private class DownloadAction implements Action {
	    @Override
	    public int getDrawable() {
	        return R.drawable.ic_download;
	    }

	    @Override
	    public void performAction(View view) {	    	
	    	Intent intent = new Intent(ImagePagerActivity.this, DownloadService.class);
			intent.putExtra("operation", DownloadService.OP_DOWNLOAD);
			String id = ids[pagerPosition];
			SkyDriveObject item = fManager.getFile(id);
			intent.putExtra("source", ((SkyDrivePhoto) item).getSource());
			intent.putExtra("name", item.getName());
			startService(intent);
	    }
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] images) {
			this.images = images;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(View view, int position) {
			final FrameLayout imageLayout = (FrameLayout) inflater.inflate(R.layout.item_pager_image, null);
			final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.pi_image);
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.pi_loading);
			
			imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
				@Override
				public void onLoadingStarted() {
					spinner.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingFailed(FailReason failReason) {
					String message = null;
					switch (failReason) {
						case IO_ERROR:
							message = "Input/Output error";
							break;
						case OUT_OF_MEMORY:
							message = "Out Of Memory error";
							break;
						case UNKNOWN:
							message = "Unknown error";
							break;
					}
					Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();

					spinner.setVisibility(View.GONE);
					imageView.setImageResource(android.R.drawable.ic_delete);
				}

				@Override
				public void onLoadingComplete() {
					spinner.setVisibility(View.GONE);
				}

				@Override
				public void onLoadingCancelled() {
					// Do nothing
				}
			});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}
}
